#coding=utf-8
from core.error import ServiceError
from .const import APPManager
from . import model
from tornado.httpclient import HTTPRequest


def wx_login_request(js_code,app_key):
    app_info = APPManager.get_app_info(app_key)
    if app_info is None:
        raise ServiceError('error key')
    url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code"
    query_data = {"js_code":js_code}
    query_data.update(app_info)
    return HTTPRequest(url=url.format(**query_data))


def xcx_login(openid):
    user_obj =model.Users.all_objects().filter(openid=openid).select()
    if not user_obj:
        new_user_obj = model.Users()
        new_user_obj.openid = openid
        new_user_obj.save()
        return new_user_obj
    else:
        #有多条记录
        return user_obj[0]



